var httpConf = require("../../../conf/httpModule.js")
var conf = require("../../../conf/niuniuConf.js").niuConf
var utils = require("../../../util/util.js")
var async = require("async")
var UUID = require('uuid');
var historyDB = require("../../../dao/history.js")
module.exports = function(app) {
	return new DBRemote(app);
};

var DBRemote = function(app) {
	this.app = app
	DBRemote.app = app
    DBRemote.dbService = this.app.get("dbService")
    if(DBRemote.dbService && DBRemote.dbService.db){
    	DBRemote.db = DBRemote.dbService.db
    }
}
var local = {}

//设置战绩
DBRemote.prototype.setHistory = function(roomId,record,MatchStream,players,cb) {

	var id = UUID.v1()+"-"+(Math.floor(Math.random() * 9000) + 1000)
	record.id = id
	//设置玩家战绩
	for(var uid in players){
		local.setPlayerHistory(uid,record)
	}
	//设置茶楼战绩
	if(parseInt(roomId) > 1000000){
		var teaId = parseInt(roomId / 100)
		var tableId = parseInt(roomId % 100)
		var maxIndex = 20
		DBRemote.dbService.db.rpush("teaHouseRecord:"+teaId,JSON.stringify(record),function(err,data) {
			console.log("rpush")
			console.log(data)
			if(data > maxIndex){
				DBRemote.dbService.db.ltrim("teaHouseRecord:"+teaId,-maxIndex,-1)
			}
		})
	}
	//保存战绩详情
	local.setHistoryDetails(id,MatchStream)
	cb()
}

//获取战绩
DBRemote.prototype.getHistory = function(uid,count,cb) {
	if(!count || typeof(count) !== "number" || count < 0){
		cb(false)
		return
	}
	DBRemote.dbService.db.lrange("game:history:"+uid,-count,-1,function(err,data) {
		cb(true,data)
	})
}

//设置玩家战绩
local.setPlayerHistory = function(uid,record) {
	var maxIndex = 20
	DBRemote.dbService.db.rpush("game:history:"+uid,JSON.stringify(record),function(err,data) {
		if(data > maxIndex){
			DBRemote.dbService.db.ltrim("game:history:"+uid,-maxIndex,-1)
		}
	})
}
//设置战绩详情
local.setHistoryDetails = function(id,MatchStream) {
	historyDB.addHistory(id,MatchStream)
}

// 获取战绩详情
DBRemote.prototype.getHistoryDetails = function(id,cb) {
	historyDB.getHistory(id,cb)
}
